package com.qymerge.manage.base.dao.impl;

import com.qymerge.manage.base.dao.IMetaBudgetProductDao;
import com.qymerge.manage.base.ro.MetaBudgetProductRO;
import com.qymerge.manage.core.bean.PageRequest;
import com.qymerge.manage.core.dao.BaseDao;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *<p>Title: MetaOrgDaoImpl</p>
 *<p>Description: 组织架构</p>
 *
 * @author Xiao
 * @date 2025/5/2 01:23
 * @version 1.0.0
 */
@Repository
public class MetaBudgetProductDaoImpl extends BaseDao implements IMetaBudgetProductDao {

//    private String dwd_MCRS_BDM_BudgetProduct = "SELECT Id,BudgetId,InternalCompanyId,MaterialId,MaterialName,MaterialCode,PackQuantity,StdPackQuantity,RevenueAmount,CostAmount,PeriodId,PeriodQuarter,PeriodMonth FROM dwd_MCRS_BDM_BudgetProduct WHERE 1=1 ";
    private String dwd_MCRS_BDM_BudgetProduct = "SELECT bp.*, c.Name as InternalCompanyName, c.Code as InternalCompanyCode  FROM dwd_MCRS_BDM_BudgetProduct bp " +
        "    left join dwd_MCRS_BDM_Budget b on bp.BudgetId = b.Id " +
        "    left join dwd_MCRS_MDM_meta_Company c on bp.InternalCompanyId = c.Id " +
        "    left join dwd_MCRS_MDM_meta_Material m on bp.MaterialId = m.Id where 1=1";

    @Override
    public List list(MetaBudgetProductRO ro, PageRequest pageRequest) {
        int skip = (pageRequest.getPage() - 1) * pageRequest.getSize();
        int size = pageRequest.getSize();

        String sql = dwd_MCRS_BDM_BudgetProduct;
        Map<String, Object> paramMap = new HashMap<String, Object>();

        sql += " and bp.BudgetId=:BudgetId";
        paramMap.put("BudgetId", ro.getBudgetId());
        
        // 分页数据获取
        sql += " order by Id desc limit :skip,:sizes";
        paramMap.put("skip", skip);
        paramMap.put("sizes", size);

        return getNamedParameterJdbcTemplate().query(sql, paramMap, new BeanPropertyRowMapper<MetaBudgetProductRO>(MetaBudgetProductRO.class));
    }

    @Override
    public int total(MetaBudgetProductRO ro) {
        String sql = "select count(1) from dwd_MCRS_BDM_BudgetProduct where 1=1";
        Map<String, Object> paramMap = new HashMap<String, Object>();

        sql += " and BudgetId=:BudgetId";
        paramMap.put("BudgetId", ro.getBudgetId());

        return getNamedParameterJdbcTemplate().queryForObject(sql, paramMap, Integer.class);
    }

    @Override
    public MetaBudgetProductRO findOne(Long id) {
        StringBuffer sql = new StringBuffer(dwd_MCRS_BDM_BudgetProduct);
        sql.append(" and bp.Id=? ");
        RowMapper<MetaBudgetProductRO> rowMapper = new BeanPropertyRowMapper<MetaBudgetProductRO>(MetaBudgetProductRO.class);
        try {
            return getJdbcTemplate().queryForObject(sql.toString(), rowMapper, id);
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public List<MetaBudgetProductRO> findAllByParentId(Long id) {
        NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(this.getJdbcTemplate());
        String sql = "select * from dwd_MCRS_BDM_BudgetProduct where ParentId in(:ids)";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("ids", id);
        return jdbc.query(sql, paramMap, new BeanPropertyRowMapper<MetaBudgetProductRO>(MetaBudgetProductRO.class));
    }

    @Override
    public int insert(MetaBudgetProductRO ro) {
        StringBuilder sql = new StringBuilder("insert into dwd_MCRS_BDM_BudgetProduct(BudgetId,InternalCompanyId,MaterialId,MaterialName,MaterialCode,PackQuantity,StdPackQuantity,RevenueAmount,CostAmount,PeriodYear,PeriodMonth) values(?,?,?,?,?,?,?,?,?,?,?)");

        List params = new ArrayList();
        params.add(ro.getBudgetId());
        params.add(ro.getInternalCompanyId());
        params.add(ro.getMaterialId());
        params.add(ro.getMaterialName());
        params.add(ro.getMaterialCode());
        params.add(ro.getPackQuantity());
        params.add(ro.getStdPackQuantity());
        params.add(ro.getRevenueAmount());
        params.add(ro.getCostAmount());
        params.add(ro.getPeriodYear());
        params.add(ro.getPeriodMonth());

        return getJdbcTemplate().update(sql.toString(), params.toArray());
    }

    @Override
    public int update(MetaBudgetProductRO ro) {
        StringBuilder sql = new StringBuilder("update dwd_MCRS_BDM_BudgetProduct set BudgetId=:BudgetId,InternalCompanyId=:InternalCompanyId,MaterialId=:MaterialId,MaterialName=MaterialName,MaterialCode=:MaterialCode,PackQuantity=:PackQuantity,StdPackQuantity=:StdPackQuantity,RevenueAmount=:RevenueAmount,CostAmount=:CostAmount,PeriodYear=:PeriodYear,PeriodMonth=:PeriodMonth where Id=:Id ");

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("BudgetId", ro.getBudgetId());
        paramsMap.put("InternalCompanyId", ro.getInternalCompanyId());
        paramsMap.put("MaterialId", ro.getMaterialId());
        paramsMap.put("MaterialName", ro.getMaterialName());
        paramsMap.put("MaterialCode", ro.getMaterialCode());
        paramsMap.put("PackQuantity", ro.getPackQuantity());
        paramsMap.put("StdPackQuantity", ro.getStdPackQuantity());
        paramsMap.put("RevenueAmount", ro.getRevenueAmount());
        paramsMap.put("CostAmount", ro.getCostAmount());
        paramsMap.put("PeriodYear", ro.getPeriodYear());
        paramsMap.put("PeriodMonth", ro.getPeriodMonth());

        paramsMap.put("Id", ro.getId());
        return getNamedParameterJdbcTemplate().update(sql.toString(), paramsMap);
    }

    @Override
    public int remove(List<Long> ids) {
        // 删除
        String sql="delete from dwd_MCRS_BDM_BudgetProduct where Id=?";
        final List<Long> idss = ids;
        BatchPreparedStatementSetter setterMid = new BatchPreparedStatementSetter(){

            @Override
            public int getBatchSize(){
                return idss.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i){
                Long id = idss.get(i);
                try {
                    ps.setLong(1, id);
                } catch(Exception e){
                    logger.error("batchInsertWaitAward Exception:", e);
                }
            }
        };

        return getJdbcTemplate().batchUpdate(sql, setterMid).length;
    }

    @Override
    public MetaBudgetProductRO findOneByYearMonthCode(Long budgetId, Integer periodYear, Integer periodMonth, String materialCode) {
        StringBuffer sql = new StringBuffer(dwd_MCRS_BDM_BudgetProduct);
        sql.append(" and bp.BudgetId=? ");
        sql.append(" and bp.PeriodYear=? ");
        sql.append(" and bp.PeriodMonth=? ");
        sql.append(" and bp.MaterialCode=? ");
        RowMapper<MetaBudgetProductRO> rowMapper = new BeanPropertyRowMapper<MetaBudgetProductRO>(MetaBudgetProductRO.class);
        try {
            return getJdbcTemplate().queryForObject(sql.toString(), rowMapper, budgetId, periodYear, periodMonth, materialCode);
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public int updatePackQuantity(MetaBudgetProductRO ro) {
        StringBuilder sql = new StringBuilder("update dwd_MCRS_BDM_BudgetProduct set PackQuantity=:PackQuantity where Id=:Id ");

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("PackQuantity", ro.getPackQuantity());
        paramsMap.put("Id", ro.getId());
        return getNamedParameterJdbcTemplate().update(sql.toString(), paramsMap);
    }

    public int updateRevenueAmount(MetaBudgetProductRO ro) {
        StringBuilder sql = new StringBuilder("update dwd_MCRS_BDM_BudgetProduct set RevenueAmount=:RevenueAmount where Id=:Id ");

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("RevenueAmount", ro.getRevenueAmount());
        paramsMap.put("Id", ro.getId());
        return getNamedParameterJdbcTemplate().update(sql.toString(), paramsMap);
    }

    public int updateCostAmount(MetaBudgetProductRO ro) {
        StringBuilder sql = new StringBuilder("update dwd_MCRS_BDM_BudgetProduct set CostAmount=:CostAmount where Id=:Id ");

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("CostAmount", ro.getCostAmount());
        paramsMap.put("Id", ro.getId());
        return getNamedParameterJdbcTemplate().update(sql.toString(), paramsMap);
    }

    @Override
    public int removeByBudgetId(Long BudgetId) {
        // 删除
        String sql="delete from dwd_MCRS_BDM_BudgetProduct where BudgetId=?";
        return getJdbcTemplate().update(sql, BudgetId);
    }


}
